package net.gyapp.markim.module.collect;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.easyder.wrapper.base.adapter.ViewHelper;
import com.easyder.wrapper.base.listener.OnViewHelper;
import com.easyder.wrapper.base.view.WrapperStatusFragment;
import com.easyder.wrapper.core.model.BaseVo;
import com.easyder.wrapper.core.network.ResponseInfo;
import com.gyf.barlibrary.ImmersionBar;

import net.gyapp.markim.ApiConfig;
import net.gyapp.markim.AppConfig;
import net.gyapp.markim.R;
import net.gyapp.markim.core.ImHelper;
import net.gyapp.markim.core.entity.ConversationEntity;
import net.gyapp.markim.core.entity.MemberEntity;
import net.gyapp.markim.dao.DBManager;
import net.gyapp.markim.dao.MemberEntityDao;
import net.gyapp.markim.module.basic.base.CommonPresenter;
import net.gyapp.markim.module.basic.event.TabChanged;
import net.gyapp.markim.module.basic.event.TabIml;
import net.gyapp.markim.module.collect.adapter.CollectAdapter;
import net.gyapp.markim.module.collect.vo.CollectionVo;
import net.gyapp.markim.module.message.ConversationActivity;
import net.gyapp.markim.module.mine.AlertTipsDialog;
import net.gyapp.markim.utils.RequestParams;

import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import butterknife.BindView;
import me.winds.widget.cluster.refresh.NestedRefreshLayout;


/**
 * Auther:  winds
 * Data:    2018/2/27
 * Version: 1.0
 * Desc:    订单
 */


public class CollectFragment extends WrapperStatusFragment<CommonPresenter> implements NestedRefreshLayout.OnRefreshListener {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.status_bar_view)
    View statusBarView;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.mNestedRefreshLayout)
    NestedRefreshLayout mNestedRefreshLayout;

    CollectAdapter adapter;

    public static CollectFragment newInstance() {
        return new CollectFragment();
    }

    @Override
    public int getViewLayout() {
        return R.layout.fragment_collect;
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        ImmersionBar.with(this).init();
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        ImmersionBar.with(this).statusBarView(statusBarView).init();
        super.initView(savedInstanceState);
        mNestedRefreshLayout.setOnRefreshListener(this);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(_mActivity));
        adapter = new CollectAdapter();
        adapter.setHeaderView(getSearchView());
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                MultiItemEntity item = adapter.getItem(position);
                if (item instanceof CollectionVo.UserCollectionsBean) {
                    CollectionVo.UserCollectionsBean bean = (CollectionVo.UserCollectionsBean) item;
                    if (bean.getItemType() == CollectAdapter.TYPE_CONTACT_USER) {
                        //用户
                        MemberEntity entity = new MemberEntity();
                        entity.memberId = bean.userInfo.userName;
                        entity.avatar = bean.userInfo.userAvatar;
                        entity.nick = bean.userInfo.nick;
                        if (entity.memberId.equalsIgnoreCase(AppConfig.NAME_ADMIN)) {
                            startActivity(ConversationActivity.getIntent(_mActivity, ImHelper.generateServiceConversation()));
                        } else {
                            if (ImHelper.isFriend(entity.memberId)) {
                                List<MemberEntity> list = DBManager.newInstance().getDaoSession().getMemberEntityDao().queryBuilder().where(MemberEntityDao.Properties.MemberId.eq(entity.memberId), MemberEntityDao.Properties.UserId.eq(ImHelper.getSelfUserId())).list();
                                if (list != null && list.size() > 0) {
                                    startActivity(ConversationActivity.getIntent(_mActivity, ImHelper.generateConversation(list.get(0))));
                                } else {
                                    startActivity(UserIntroduceActivity.getIntent(_mActivity, entity));
                                }
                            } else {
                                startActivity(UserIntroduceActivity.getIntent(_mActivity, entity));
                            }
                        }

                    } else if (bean.getItemType() == CollectAdapter.TYPE_CONTACT_GROUP) {
                        ConversationEntity entity = ImHelper.generateConversation(bean.groupInfo.groupNumber);
                        if (entity != null) {
                            startActivity(ConversationActivity.getIntent(_mActivity, entity));
                        } else {//提示添加群
                            showGroupTips(bean.groupInfo.groupNumber);
                        }
                    }
                }
            }
        });
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        onRefresh();
    }

    @Override
    protected void loadData(Bundle savedInstanceState) {

    }

    @Override
    public void showContentView(String url, BaseVo dataVo) {
        super.showContentView(url, dataVo);
        if (url.contains(ApiConfig.API_GET_COLLECTIONS)) {
            processData((CollectionVo) dataVo);
        } else if (url.contains(ApiConfig.API_JOIN_GROUP)) {
            showToast("申请已提交");
        }
    }

    @Override
    public void onError(ResponseInfo responseInfo) {
        super.onError(responseInfo);
        mNestedRefreshLayout.refreshFinish();
    }

    @Override
    public void onRefresh() {
        getCollections();
    }

    @Override
    protected boolean isLazyLoad() {
        return true;
    }

    @Subscribe
    public void tabChanged(TabChanged changed) {
        if (changed.sign == TabIml.SIGN_TAB_COLLECT) {
            getCollections();
        }
    }

    private void getCollections() {
        presenter.setNeedDialog(false);
        presenter.postData(ApiConfig.API_GET_COLLECTIONS, CollectionVo.class);
    }


    private void processData(CollectionVo dataVo) {
        mNestedRefreshLayout.refreshFinish();
        adapter.setAdapterData(dataVo);
    }

    private View getSearchView() {
        return getHelperView(mRecyclerView, R.layout.header_collect_search, new OnViewHelper() {
            @Override
            public void help(ViewHelper helper) {
                EditText etInput = helper.getView(R.id.et_input);
                etInput.setImeActionLabel("搜索", EditorInfo.IME_ACTION_SEARCH);
                etInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_SEARCH && v.getId() == R.id.et_input) {
                            String s = v.getText().toString();
                            if (!TextUtils.isEmpty(s)) {
                                search(s);
                            }
                        }
                        return false;
                    }
                });
            }
        });
    }

    private void search(String keyword) {

    }

    private void applyJoinGroup(String groupNumber) {
        presenter.setNeedDialog(true);
        presenter.postData(ApiConfig.API_JOIN_GROUP, new RequestParams().put("groupNumber", groupNumber).get(), BaseVo.class);
    }


    private void showGroupTips(final String groupNumber) {
        new AlertTipsDialog(_mActivity).setUp(new AlertTipsDialog.OnConfirmListener() {
            @Override
            public void onConfirm(Dialog dialog, View view) {
                dialog.dismiss();
                applyJoinGroup(groupNumber);
            }
        }, "您还未添加该群组，申请加入", "确认", "取消").show();
    }
}
